<script setup lang="ts">
import { ref, reactive, onMounted, h, nextTick, computed, watch } from "vue";
import { useRoute } from "vue-router";
import { DynamicTable } from "@/components/DynamicTable";
import { TableColumn } from "@/components/DynamicTable/types";
import DynamicForm from "@/components/DynamicForm/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import { FormItemConfig } from "@/components/DynamicForm/types";
import {
  ElMessage,
  ElMessageBox,
  ElTag,
  ElButton,
  ElDialog,
  ElDescriptions,
  ElDescriptionsItem,
  ElSelect,
  ElOption,
  ElDivider,
  ElCard,
  ElCollapse,
  ElCollapseItem,
} from "element-plus";
import {
  Refresh,
  Plus,
  Edit,
  Delete,
  ArrowUp,
  ArrowDown,
  InfoFilled,
  View,
} from "@element-plus/icons-vue";
import {
  getDimensionList,
  createDimension,
  updateDimension,
  deleteDimension,
  reorderDimensions,
  testDimensionCalculation,
  getDimensionDetail,
  getScoreTemplateList,
} from "../servers";

const route = useRoute();

const loading = ref(false);
const dimensionList = ref<any[]>([]);
const templateList = ref<any[]>([]);
const selectedTemplateId = ref<number | null>(null);
const selectedDimension = ref<any>(null);
const formRef = ref<DynamicFormInstance>();

const showDetailDialog = ref(false);
const showEditDialog = ref(false);
const isEdit = ref(false);
const currentDimension = ref<any>(null);

// 从路由参数获取template_id
watch(
  () => route.query.template_id,
  (newId) => {
    if (newId) {
      selectedTemplateId.value = Number(newId);
      fetchDimensionList();
    }
  },
  { immediate: true }
);

const formData = reactive({
  dimension_code: "",
  dimension_name: "",
  description: "",
  max_score: 30,
  weight: 1.0,
  display_order: 1,
  calculation_type: "level_mapping",
  calculation_config: {},
  data_source_type: "single_table",
  data_source_table: "",
  query_conditions: "",
  aggregation_method: "max",
  is_enabled: true,
  // 级别映射配置
  level_critical: 30,
  level_high: 20,
  level_medium: 10,
  level_low: 5,
  // 数量乘数配置
  enable_quantity_multiplier: false,
  multiplier_1: 1.0,
  multiplier_2: 1.1,
  multiplier_3_plus: 1.2,
});

const columns = ref<TableColumn[]>([
  {
    label: "序号",
    prop: "display_order",
    width: 80,
    show: true,
  },
  {
    label: "维度名称",
    prop: "dimension_name",
    minWidth: 150,
    show: true,
  },
  {
    label: "维度代码",
    prop: "dimension_code",
    minWidth: 150,
    show: true,
  },
  {
    label: "最大扣分",
    prop: "max_score",
    width: 100,
    show: true,
    render: (row) => {
      return h("span", {}, `${row.max_score}分`);
    },
  },
  {
    label: "权重",
    prop: "weight",
    width: 100,
    show: true,
  },
  {
    label: "计算类型",
    prop: "calculation_type",
    width: 120,
    show: true,
    render: (row) => {
      const typeMap: Record<string, string> = {
        level_mapping: "级别映射",
        weighted_sum: "加权组合",
        quantity_multiplier: "数量系数",
        custom_formula: "自定义公式",
      };
      return h(
        ElTag,
        { type: "info", size: "small" },
        typeMap[row.calculation_type] || row.calculation_type
      );
    },
  },
  {
    label: "状态",
    prop: "is_enabled",
    width: 100,
    show: true,
    render: (row) => {
      const statusMap: Record<string, any> = {
        true: { text: "✅ 启用", type: "success" },
        false: { text: "⏸️ 停用", type: "info" },
      };
      const statusInfo = statusMap[row.is_enabled] || {
        text: "未知",
        type: "info",
      };
      return h(
        ElTag,
        { type: statusInfo.type, size: "small" },
        statusInfo.text
      );
    },
  },
  {
    label: "操作",
    prop: "action",
    width: 280,
    fixed: "right",
    show: true,
    slot: "action",
  },
]);

// 获取模板列表
const fetchTemplateList = async () => {
  try {
    const { data } = await getScoreTemplateList();
    const templates = data?.templates || data || [];
    templateList.value = templates.map((t: any) => ({
      label: t.template_name || t.name,
      value: t.id || t.template_id,
    }));

    // 如果没有选择模板且列表不为空，默认选择第一个
    if (!selectedTemplateId.value && templateList.value.length > 0) {
      selectedTemplateId.value = templateList.value[0].value;
      fetchDimensionList();
    }
  } catch (error) {
    console.error("获取模板列表失败:", error);
  }
};

// 获取维度列表
const fetchDimensionList = async () => {
  if (!selectedTemplateId.value) {
    ElMessage.warning("请先选择模板");
    return;
  }

  loading.value = true;
  try {
    const { data } = await getDimensionList({
      template_id: selectedTemplateId.value,
    });
    dimensionList.value = data?.dimensions || data || [];
    // 按display_order排序
    dimensionList.value.sort(
      (a, b) => (a.display_order || 0) - (b.display_order || 0)
    );
  } catch (error) {
    ElMessage.error("获取维度列表失败");
  } finally {
    loading.value = false;
  }
};

// 选择模板
const handleTemplateChange = () => {
  selectedDimension.value = null;
  fetchDimensionList();
};

// 查看详情
const handleViewDetail = async (row: any) => {
  try {
    const { data } = await getDimensionDetail({ id: row.id });
    selectedDimension.value = data?.dimension || data || row;
    showDetailDialog.value = true;
  } catch (error) {
    ElMessage.error("获取维度详情失败");
    selectedDimension.value = row;
    showDetailDialog.value = true;
  }
};

// 新建维度
const handleCreate = () => {
  isEdit.value = false;
  Object.assign(formData, {
    dimension_code: "",
    dimension_name: "",
    description: "",
    max_score: 30,
    weight: 1.0,
    display_order: dimensionList.value.length + 1,
    calculation_type: "level_mapping",
    calculation_config: {},
    data_source_type: "single_table",
    data_source_table: "",
    query_conditions: "",
    aggregation_method: "max",
    is_enabled: true,
    level_critical: 30,
    level_high: 20,
    level_medium: 10,
    level_low: 5,
    enable_quantity_multiplier: false,
    multiplier_1: 1.0,
    multiplier_2: 1.1,
    multiplier_3_plus: 1.2,
  });
  showEditDialog.value = true;
  nextTick(() => {
    formRef.value?.resetFields();
  });
};

// 编辑维度
const handleEdit = (dimension: any) => {
  isEdit.value = true;
  currentDimension.value = dimension;
  const config = dimension.calculation_config || {};
  Object.assign(formData, {
    dimension_code: dimension.dimension_code || "",
    dimension_name: dimension.dimension_name || "",
    description: dimension.description || "",
    max_score: dimension.max_score || 30,
    weight: dimension.weight || 1.0,
    display_order: dimension.display_order || 1,
    calculation_type: dimension.calculation_type || "level_mapping",
    calculation_config: config,
    data_source_type: dimension.data_source_type || "single_table",
    data_source_table: dimension.data_source_table || "",
    query_conditions:
      typeof dimension.query_conditions === "string"
        ? dimension.query_conditions
        : JSON.stringify(dimension.query_conditions || {}, null, 2),
    aggregation_method: dimension.aggregation_method || "max",
    is_enabled: dimension.is_enabled !== false,
    level_critical: config.critical || 30,
    level_high: config.high || 20,
    level_medium: config.medium || 10,
    level_low: config.low || 5,
    enable_quantity_multiplier: config.enable_quantity_multiplier || false,
    multiplier_1: config.multiplier_1 || 1.0,
    multiplier_2: config.multiplier_2 || 1.1,
    multiplier_3_plus: config.multiplier_3_plus || 1.2,
  });
  showEditDialog.value = true;
  nextTick(() => {
    formRef.value?.resetFields();
  });
};

// 提交表单
const handleSubmit = async (values: any) => {
  try {
    // 构建calculation_config
    const calculationConfig: any = {};
    if (values.calculation_type === "level_mapping") {
      calculationConfig.critical = values.level_critical;
      calculationConfig.high = values.level_high;
      calculationConfig.medium = values.level_medium;
      calculationConfig.low = values.level_low;
      if (values.enable_quantity_multiplier) {
        calculationConfig.enable_quantity_multiplier = true;
        calculationConfig.multiplier_1 = values.multiplier_1;
        calculationConfig.multiplier_2 = values.multiplier_2;
        calculationConfig.multiplier_3_plus = values.multiplier_3_plus;
      }
    }

    // 解析query_conditions
    let queryConditions: any = {};
    try {
      queryConditions =
        typeof values.query_conditions === "string"
          ? JSON.parse(values.query_conditions || "{}")
          : values.query_conditions || {};
    } catch (e) {
      ElMessage.warning("查询条件JSON格式错误，将使用空对象");
    }

    if (isEdit.value) {
      // 更新维度
      await updateDimension({
        id: currentDimension.value.id,
        dimension_name: values.dimension_name,
        description: values.description,
        max_score: values.max_score,
        weight: values.weight,
        display_order: values.display_order,
        calculation_type: values.calculation_type,
        calculation_config: calculationConfig,
        data_source_type: values.data_source_type,
        data_source_table: values.data_source_table,
        query_conditions: queryConditions,
        aggregation_method: values.aggregation_method,
        is_enabled: values.is_enabled,
      });
      ElMessage.success("更新维度成功");
    } else {
      // 创建维度
      await createDimension({
        template_id: selectedTemplateId.value!,
        dimension_code: values.dimension_code,
        dimension_name: values.dimension_name,
        description: values.description,
        max_score: values.max_score,
        weight: values.weight,
        display_order: values.display_order,
        calculation_type: values.calculation_type,
        calculation_config: calculationConfig,
        data_source_type: values.data_source_type,
        data_source_table: values.data_source_table,
        query_conditions: queryConditions,
        aggregation_method: values.aggregation_method,
        is_enabled: values.is_enabled,
      });
      ElMessage.success("创建维度成功");
    }
    showEditDialog.value = false;
    fetchDimensionList();
  } catch (error: any) {
    ElMessage.error(error.message || "操作失败");
  }
};

// 删除维度
const handleDelete = async (dimension: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除维度 "${dimension.dimension_name}" 吗？`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );
    await deleteDimension({ id: dimension.id });
    ElMessage.success("删除成功");
    fetchDimensionList();
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error(error.message || "删除失败");
    }
  }
};

// 上移
const handleMoveUp = async (index: number) => {
  if (index === 0) return;
  const dimensions = [...dimensionList.value];
  [dimensions[index - 1], dimensions[index]] = [
    dimensions[index],
    dimensions[index - 1],
  ];
  await saveOrder(dimensions);
};

// 下移
const handleMoveDown = async (index: number) => {
  if (index === dimensionList.value.length - 1) return;
  const dimensions = [...dimensionList.value];
  [dimensions[index], dimensions[index + 1]] = [
    dimensions[index + 1],
    dimensions[index],
  ];
  await saveOrder(dimensions);
};

// 保存顺序
const saveOrder = async (dimensions: any[]) => {
  try {
    const dimensionOrders = dimensions.map((dim, index) => ({
      id: dim.id,
      display_order: index + 1,
    }));
    await reorderDimensions({
      template_id: selectedTemplateId.value!,
      dimension_orders: dimensionOrders,
    });
    ElMessage.success("调整顺序成功");
    fetchDimensionList();
  } catch (error: any) {
    ElMessage.error(error.message || "调整顺序失败");
  }
};

// 测试计算
const handleTest = async (dimension: any) => {
  try {
    ElMessage.info("测试计算功能开发中");
    // const { data } = await testDimensionCalculation({
    //   dimension_id: dimension.id,
    // });
    // ElMessage.success("测试成功");
  } catch (error: any) {
    ElMessage.error(error.message || "测试失败");
  }
};

// 表单配置
const formConfig = computed<FormItemConfig[]>(() => [
  {
    key: "dimension_code",
    name: "维度代码",
    type: "input",
    labelWidth: "140px",
    placeholder: "请输入维度代码（仅字母、数字、下划线）",
    rules: [{ required: true, message: "请输入维度代码" }],
    show: () => !isEdit.value,
  },
  {
    key: "dimension_name",
    name: "维度名称",
    type: "input",
    labelWidth: "140px",
    placeholder: "请输入维度名称",
    rules: [{ required: true, message: "请输入维度名称" }],
  },
  {
    key: "description",
    name: "描述",
    type: "textarea",
    labelWidth: "140px",
    placeholder: "请输入描述",
    params: {
      rows: 2,
    },
  },
  {
    key: "max_score",
    name: "最大扣分",
    type: "number",
    labelWidth: "140px",
    placeholder: "请输入最大扣分",
    params: {
      min: 0,
      max: 100,
    },
    rules: [{ required: true, message: "请输入最大扣分" }],
  },
  {
    key: "weight",
    name: "权重系数",
    type: "number",
    labelWidth: "140px",
    placeholder: "请输入权重系数",
    params: {
      min: 0,
      max: 10,
      step: 0.1,
      precision: 1,
    },
    rules: [{ required: true, message: "请输入权重系数" }],
  },
  {
    key: "display_order",
    name: "显示顺序",
    type: "number",
    labelWidth: "140px",
    placeholder: "请输入显示顺序",
    params: {
      min: 1,
    },
  },
  {
    key: "data_source_type",
    name: "数据源类型",
    type: "radio",
    labelWidth: "140px",
    params: {
      options: [
        { label: "单表查询", value: "single_table" },
        { label: "多表JOIN", value: "multi_table" },
        { label: "自定义", value: "custom" },
      ],
    },
  },
  {
    key: "data_source_table",
    name: "数据源表",
    type: "input",
    labelWidth: "140px",
    placeholder: "请输入数据源表名",
    show: (formData) => formData.data_source_type !== "custom",
  },
  {
    key: "query_conditions",
    name: "查询条件",
    type: "textarea",
    labelWidth: "140px",
    placeholder: '请输入查询条件JSON，如: {"ip": "asset_ip"}',
    params: {
      rows: 3,
    },
    show: (formData) => formData.data_source_type !== "custom",
  },
  {
    key: "calculation_type",
    name: "计算类型",
    type: "select",
    labelWidth: "140px",
    placeholder: "选择计算类型",
    rules: [{ required: true, message: "请选择计算类型" }],
    params: {
      options: [
        { label: "级别映射", value: "level_mapping" },
        { label: "加权组合", value: "weighted_sum" },
        { label: "数量系数", value: "quantity_multiplier" },
        { label: "自定义公式", value: "custom_formula" },
      ],
    },
  },
  // 级别映射配置
  {
    key: "level_critical",
    name: "critical扣分",
    type: "number",
    labelWidth: "140px",
    placeholder: "请输入critical级别扣分",
    params: {
      min: 0,
      max: 100,
    },
    show: (formData) => formData.calculation_type === "level_mapping",
  },
  {
    key: "level_high",
    name: "high扣分",
    type: "number",
    labelWidth: "140px",
    placeholder: "请输入high级别扣分",
    params: {
      min: 0,
      max: 100,
    },
    show: (formData) => formData.calculation_type === "level_mapping",
  },
  {
    key: "level_medium",
    name: "medium扣分",
    type: "number",
    labelWidth: "140px",
    placeholder: "请输入medium级别扣分",
    params: {
      min: 0,
      max: 100,
    },
    show: (formData) => formData.calculation_type === "level_mapping",
  },
  {
    key: "level_low",
    name: "low扣分",
    type: "number",
    labelWidth: "140px",
    placeholder: "请输入low级别扣分",
    params: {
      min: 0,
      max: 100,
    },
    show: (formData) => formData.calculation_type === "level_mapping",
  },
  {
    key: "enable_quantity_multiplier",
    name: "启用数量乘数",
    type: "switch",
    labelWidth: "140px",
    show: (formData) => formData.calculation_type === "level_mapping",
  },
  {
    key: "multiplier_1",
    name: "1个倍数",
    type: "number",
    labelWidth: "140px",
    params: {
      min: 0,
      max: 10,
      step: 0.1,
      precision: 1,
    },
    show: (formData) =>
      formData.calculation_type === "level_mapping" &&
      formData.enable_quantity_multiplier,
  },
  {
    key: "multiplier_2",
    name: "2个倍数",
    type: "number",
    labelWidth: "140px",
    params: {
      min: 0,
      max: 10,
      step: 0.1,
      precision: 1,
    },
    show: (formData) =>
      formData.calculation_type === "level_mapping" &&
      formData.enable_quantity_multiplier,
  },
  {
    key: "multiplier_3_plus",
    name: "3个+倍数",
    type: "number",
    labelWidth: "140px",
    params: {
      min: 0,
      max: 10,
      step: 0.1,
      precision: 1,
    },
    show: (formData) =>
      formData.calculation_type === "level_mapping" &&
      formData.enable_quantity_multiplier,
  },
  {
    key: "aggregation_method",
    name: "聚合方式",
    type: "radio",
    labelWidth: "140px",
    params: {
      options: [
        { label: "max (取最大值)", value: "max" },
        { label: "sum (求和)", value: "sum" },
        { label: "avg (平均值)", value: "avg" },
        { label: "weighted (加权)", value: "weighted" },
      ],
    },
  },
  {
    key: "is_enabled",
    name: "启用此维度",
    type: "switch",
    labelWidth: "140px",
    defaultValue: true,
  },
]);

onMounted(() => {
  fetchTemplateList();
  if (route.query.template_id) {
    selectedTemplateId.value = Number(route.query.template_id);
    fetchDimensionList();
  }
});
</script>

<template>
  <div>
    <!-- 模板选择 -->
    <el-card shadow="never">
      <div style="display: flex; align-items: center; gap: 16px">
        <span style="font-weight: bold">当前模板:</span>
        <el-select
          v-model="selectedTemplateId"
          placeholder="请选择模板"
          style="width: 300px"
          @change="handleTemplateChange"
        >
          <el-option
            v-for="template in templateList"
            :key="template.value"
            :label="template.label"
            :value="template.value"
          />
        </el-select>
        <el-button
          type="info"
          :icon="Refresh"
          @click="fetchDimensionList"
          :loading="loading"
        >
          刷新
        </el-button>
      </div>
    </el-card>

    <div style="height: 10px"></div>

    <!-- 维度列表 -->
    <el-card>
      <DynamicTable
        :columns="columns"
        :data="dimensionList"
        :loading="loading"
        :show-pagination="false"
      >
        <template #toolbar-left>
          <el-button
            type="primary"
            :icon="Plus"
            @click="handleCreate"
            :disabled="!selectedTemplateId"
          >
            添加维度
          </el-button>
        </template>

        <template #action="{ row, index }">
          <el-button
            type="primary"
            size="small"
            :icon="View"
            @click="handleViewDetail(row)"
          >
            详情
          </el-button>
          <el-button
            type="warning"
            size="small"
            :icon="Edit"
            @click="handleEdit(row)"
          >
            编辑
          </el-button>
          <el-button
            type="info"
            size="small"
            :icon="ArrowUp"
            :disabled="index === 0"
            @click="handleMoveUp(index)"
          >
            上移
          </el-button>
          <el-button
            type="info"
            size="small"
            :icon="ArrowDown"
            :disabled="index === dimensionList.length - 1"
            @click="handleMoveDown(index)"
          >
            下移
          </el-button>
          <el-button
            type="danger"
            size="small"
            :icon="Delete"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </DynamicTable>
    </el-card>

    <!-- 维度详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      :title="
        selectedDimension
          ? `维度详情 - ${selectedDimension.dimension_name}`
          : '维度详情'
      "
      width="900px"
      destroy-on-close
    >
      <div v-if="selectedDimension">
        <el-descriptions title="基础信息" :column="2" border>
          <el-descriptions-item label="维度名称">
            {{ selectedDimension.dimension_name }}
          </el-descriptions-item>
          <el-descriptions-item label="维度代码">
            {{ selectedDimension.dimension_code }}
          </el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">
            {{ selectedDimension.description || "无" }}
          </el-descriptions-item>
          <el-descriptions-item label="最大扣分">
            <span style="font-weight: bold; font-size: 16px"
              >{{ selectedDimension.max_score }}分</span
            >
          </el-descriptions-item>
          <el-descriptions-item label="权重系数">
            {{ selectedDimension.weight }}
          </el-descriptions-item>
          <el-descriptions-item label="显示顺序">
            {{ selectedDimension.display_order }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag
              :type="selectedDimension.is_enabled ? 'success' : 'info'"
              size="small"
            >
              {{ selectedDimension.is_enabled ? "✅ 启用" : "⏸️ 停用" }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <el-divider />

        <el-descriptions title="数据源配置" :column="1" border>
          <el-descriptions-item label="数据源类型">
            {{
              selectedDimension.data_source_type === "single_table"
                ? "单表查询"
                : selectedDimension.data_source_type === "multi_table"
                ? "多表JOIN"
                : "自定义"
            }}
          </el-descriptions-item>
          <el-descriptions-item
            v-if="selectedDimension.data_source_table"
            label="数据源表"
          >
            {{ selectedDimension.data_source_table }}
          </el-descriptions-item>
          <el-descriptions-item
            v-if="selectedDimension.query_conditions"
            label="查询条件"
          >
            <pre
              style="
                margin: 0;
                white-space: pre-wrap;
                background: #f5f7fa;
                padding: 10px;
                border-radius: 4px;
              "
              >{{
                typeof selectedDimension.query_conditions === "string"
                  ? selectedDimension.query_conditions
                  : JSON.stringify(selectedDimension.query_conditions, null, 2)
              }}</pre
            >
          </el-descriptions-item>
        </el-descriptions>

        <el-divider />

        <el-descriptions title="计算规则" :column="1" border>
          <el-descriptions-item label="计算类型">
            <el-tag type="info">
              {{
                selectedDimension.calculation_type === "level_mapping"
                  ? "级别映射"
                  : selectedDimension.calculation_type === "weighted_sum"
                  ? "加权组合"
                  : selectedDimension.calculation_type === "quantity_multiplier"
                  ? "数量系数"
                  : "自定义公式"
              }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item
            v-if="selectedDimension.calculation_config"
            label="规则配置"
          >
            <div
              v-if="
                selectedDimension.calculation_type === 'level_mapping' &&
                selectedDimension.calculation_config
              "
            >
              <el-collapse>
                <el-collapse-item title="级别映射配置">
                  <div style="padding: 10px">
                    <p>
                      <strong>critical:</strong>
                      {{ selectedDimension.calculation_config.critical || 0 }}分
                    </p>
                    <p>
                      <strong>high:</strong>
                      {{ selectedDimension.calculation_config.high || 0 }}分
                    </p>
                    <p>
                      <strong>medium:</strong>
                      {{ selectedDimension.calculation_config.medium || 0 }}分
                    </p>
                    <p>
                      <strong>low:</strong>
                      {{ selectedDimension.calculation_config.low || 0 }}分
                    </p>
                  </div>
                </el-collapse-item>
                <el-collapse-item
                  v-if="
                    selectedDimension.calculation_config
                      .enable_quantity_multiplier
                  "
                  title="数量乘数配置"
                >
                  <div style="padding: 10px">
                    <p>
                      <strong>1个漏洞:</strong>
                      {{
                        selectedDimension.calculation_config.multiplier_1 ||
                        1.0
                      }}倍
                    </p>
                    <p>
                      <strong>2个漏洞:</strong>
                      {{
                        selectedDimension.calculation_config.multiplier_2 ||
                        1.1
                      }}倍
                    </p>
                    <p>
                      <strong>3个+漏洞:</strong>
                      {{
                        selectedDimension.calculation_config
                          .multiplier_3_plus || 1.2
                      }}倍
                    </p>
                  </div>
                </el-collapse-item>
              </el-collapse>
            </div>
            <pre
              v-else
              style="
                margin: 0;
                white-space: pre-wrap;
                background: #f5f7fa;
                padding: 10px;
                border-radius: 4px;
              "
              >{{
                JSON.stringify(selectedDimension.calculation_config, null, 2)
              }}</pre
            >
          </el-descriptions-item>
          <el-descriptions-item label="聚合方式">
            {{
              selectedDimension.aggregation_method === "max"
                ? "max (取最大值)"
                : selectedDimension.aggregation_method === "sum"
                ? "sum (求和)"
                : selectedDimension.aggregation_method === "avg"
                ? "avg (平均值)"
                : selectedDimension.aggregation_method === "weighted"
                ? "weighted (加权)"
                : selectedDimension.aggregation_method
            }}
          </el-descriptions-item>
        </el-descriptions>

        <el-divider />

        <div style="display: flex; gap: 8px; justify-content: flex-end">
          <el-button
            type="primary"
            :icon="Edit"
            @click="
              () => {
                showDetailDialog = false;
                handleEdit(selectedDimension);
              }
            "
          >
            编辑配置
          </el-button>
          <el-button
            type="warning"
            :icon="InfoFilled"
            @click="handleTest(selectedDimension)"
          >
            测试计算
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 编辑维度对话框 -->
    <el-dialog
      v-model="showEditDialog"
      :title="isEdit ? '编辑评分维度' : '添加评分维度'"
      width="800px"
      destroy-on-close
      @close="
        () => {
          showEditDialog = false;
          formRef?.resetFields();
        }
      "
    >
      <DynamicForm
        ref="formRef"
        v-model="formData"
        :form-config="formConfig"
        :gutter="16"
        type="submit"
        @submit="handleSubmit"
        @cancel="
          () => {
            showEditDialog = false;
            formRef?.resetFields();
          }
        "
      />
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
:deep(.el-descriptions__label) {
  font-weight: 500;
}
</style>
